<?php
class ItemsController extends AppController {

	var $name = 'Items';
	var $components = array('LogUtil','RequestHandler','Image');
	var $uses = array('Item','Location');
	var $helpers = array('Barcode','Js' => 'Jquery','Number','Html', 'Form', 'FileUpload.FileUpload' );
	var $paginate = array('limit' => 15);
	var $location = 'locations';

	function beforeFilter(){
        parent::beforeFilter();
        
    }
    
	function generateRange($start_date, $end_date = null) {
		prd ( "calling range" );
	}
    
	function index() {

		$options = array();
		if(isset($this->data)) {
			$post = $this->data['Item'];
			$dtfrom = date("Y-m-d", strtotime($post['datefrom']));
			$dtto = date("Y-m-d", strtotime($post['dateto']));
			
			$conditions = array('Item.received_date >='=>$dtfrom,
								'Item.received_date <='=>$dtto
			);
		
		if(!empty($this->data)) {
			if(!empty($this->data['Items']['category_id']))
			$options['Category.id'] = $this->data['Items']['category_id'];
			if(!empty($this->data['Items']['type_id']))
			$options['Type.id'] = $this->data['Items']['type_id'];
			/*if(!empty($this->data['Items']['received_date'])){
				$time = $this->data['Items']['received_date'];
				$dateObject = new DateTime($time);
				$options['Item.received_date'] = $dateObject->format("Y-m-d");
			}*/
			if(!empty($this->data['Items']['q'])) {
				$options['OR']['Type.name LIKE'] = $this->data['Items']['q'].'%';
				$options['OR']['Item.name LIKE'] = $this->data['Items']['q'].'%';
				//$options['OR']['Type.received_date'] = $this->data['Item']['received_date'];
			}
		}
		
		$this->set('datefrom',$this->data['Item']['datefrom']);
		$this->set('dateto',$this->data['Item']['dateto']);
		
		}

		$this->Item->recursive = 0;
		$this->set('items', $this->paginate($options));
		$this->set('title_for_layout', 'Asset Management System PDRM');
		$categories = $this->Item->Category->find('list');
		$this->set(compact('categories'));
		$types = $this->Item->Type->find('list');
		$this->set(compact('types'));
		$this->layout = 'default';
		

	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid item', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!$id) {
			$this->Session->setFlash(__('Invalid image', true));
			$this->redirect(array('action' => 'index'));
		}

		$item = $this->Item->read(null, $id);
		$this->set('item', $item);

		$locations = $this->Item->Location->find('all',array('conditions'=>array('Location.item_id'=>$id)));
		$this->set('locations',$locations);

		$inspections = $this->Item->Inspection->find('all',array('conditions'=>array('Inspection.item_id'=>$id)));
		$this->set('inspections',$inspections);

		$disposals = $this->Item->Disposal->find('all',array('conditions'=>array('Disposal.item_id'=>$id)));
		$this->set('disposals',$disposals);
		//$this->image->resize($item['Item']['image_url'], 150, 150, true);
		//$this->imageSize->crop($item['Item']['image_url']);
		//$images = $this->Item->Image->find('list');
		//$this->set('images',$images);
		//$images = $this->Item->image($item['Item']['image_url'], 150, 150, true);
		
		$this->set('nosiri',$this->Item->generateSerialNo($id));
		//$this->set('image', $this->Image->read(null, $id));
		
		//$this->imageSize->crop($item['Item']['image_url'], 40, 40);
		//$this->imageSizeHelper->crop();
		
		/*$current_date = date('Ymd');
		 if ( $this->data['Item']['warranty_period'] < $current_date ){
			echo $this->Item->highlight($item['Item']['warranty_period']);
			}

			if($this->Item->isWarantyExpired($item['id'])) {
			$this->set('penanda',true);
			}*/
		//pr($item);
		//exit;
		

	}

	function add() {
		if (!empty($this->data)) {
			$time = $this->data['Item']['received_date'];
			//$ymd = $time['year']."-".$time['month']."-".$time['day'];
			$dateObject = new DateTime($time);
			$tjs = $this->add_date($dateObject->format("Y-m-d"), $this->data['Item']['warranty_period']['type'], $this->data['Item']['warranty_period']['period']);
			$this->data['Item']['warranty_period'] = $tjs;
			//$tjs = $this->add_date($ymd, $this->data['Item']['warranty_period']['type'], $this->data['Item']['warranty_period']['period']);
			//$this->data['Item']['warranty_period'] = $tjs;
			
			
			$this->data['Item']['received_date'] = $dateObject->format("y-m-d");
			//$this->data['Item']['received_date'] = date("d-M-Y", strtotime($this->data['Item']['received_date']));

			$tar = $this->data['Item']['ownership_date'];
			$dateOwnership = new DateTime($tar);
			$this->data['Item']['ownership_date'] = $dateOwnership->format("y-m-d");
			
			// upload the file to the server
			$fileOK = $this->uploadFiles('img/files', $this->data['File']);

			// if file was uploaded ok
			if(array_key_exists('urls', $fileOK)) {
				// save the url in the form data
				$this->data['Item']['image_url'] = $fileOK['urls'][0];
			}
			$this->Location->set($this->data);
			
			if($this->Location->validates()) {
				$this->Location->Item->create();
			if ($this->Item->save($this->data)) {
				$this->data['Location']['item_id'] = $this->Item->getLastInsertId();
				$this->data['Location']['active'] = 1;
				$this->data['Location']['date'] = date("Y-m-d", strtotime($this->data['Location']['date']));
				//$this->data['Location']['date'] = date("d-M-Y");
			}else {
				$errors = $this->Location->invalidFields();
			}
				
			
				$this->Location->save($this->data);
				$this->Session->setFlash(__('The item has been saved','flash_good'));
				$this->redirect(array('action' => 'view',$this->Item->getLastInsertId()));
			} else {
				$this->Session->setFlash(__('The item could not be saved. Please, try again.', true));
			}
		}

		$categories = $this->Item->Category->find('list');
		$types = $this->Item->Type->find('list');
		$origins = $this->Item->Origin->find('list');
		$suppliers = $this->Item->Supplier->find('list');
		$ownerships = $this->Item->Ownership->find('list');
		$districts = $this->Location->District->find('list');
		$contingents = $this->Location->District->Contingent->find('list');
		$this->set(compact('categories', 'types', 'origins', 'suppliers', 'ownerships', 'districts', 'contingents'));
		/*$galleries = $this->Image->Gallery->find('list');
		 $this->set(compact('galleries'));*/

	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid item', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			$time = $this->data['Item']['received_date'];
			$dateObject = new DateTime($time);
			$tjs = $this->add_date($dateObject->format("Y-m-d"), $this->data['Item']['warranty_period']['type'], $this->data['Item']['warranty_period']['period']);
			$this->data['Item']['warranty_period'] = $tjs;
			
			$tar = $this->data['Item']['ownership_date'];
			$dateOwnership = new DateTime($tar);
			$this->data['Item']['ownership_date'] = $dateOwnership->format("y-m-d");
			
			// upload the file to the server
			$fileOK = $this->uploadFiles('img/files', $this->data['File']);
			$this->data['Item']['received_date'] = $dateObject->format("y-m-d");

			// if file was uploaded ok
			if(array_key_exists('urls', $fileOK)) {
				// save the url in the form data
				$this->data['Item']['image_url'] = $fileOK['urls'][0];
			}
				
			if ($this->Item->save($this->data)) {
				$this->Session->setFlash(__('The item has been saved', true));
				$this->redirect(array('action' => 'view',$id));

			} else {
				$this->Session->setFlash(__('The item could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Item->read(null, $id);
		}
		$inspections = $this->Item->Inspection->find('list');
		$categories = $this->Item->Category->find('list');
		$types = $this->Item->Type->find('list');
		$origins = $this->Item->Origin->find('list');
		$suppliers = $this->Item->Supplier->find('list');
		$ownerships = $this->Item->Ownership->find('list');
		$items = $this->Item->find('list');
		$this->set('item',$this->data);
		$this->set(compact('categories', 'types', 'origins', 'suppliers', 'ownerships', 'inspections'));

	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for item', true));
			$this->redirect(array('action'=>'index'));
		}
		
		/*
		$upload = $this->Upload->findById($id);
        if($this->FileUpload->removeFile($upload['Upload']['name'])){
           if($this->Upload->delete($id)){
                $this->Session->setFlash('Upload deleted');
                $this->redirect(array('action'=>'index'));
           }
        }*/
		
		if ($this->Item->delete($id)) {
			$this->Session->setFlash(__('Item deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Item was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}

	function test() {
		$this->Item->recursive = -1;
		$item = $this->Item->findAllById(2);
		echo $item[0]["Item"]['type_id'];
		exit;
	}

	function search($qid = null){
		if(!empty($this->data)) {
			$q = $this->data['Item']['q'];
			$qid =  substr($q,-6, 6);
			$item = $this->Item->find("first",array('conditions' => array('Item.id' => $qid)));
			$result = (empty($item)) ? "TIADA MAKLUMAT" : "";
			$this->set('item',$item);
		}else {
			$result = "SILA MASUKKAN MAKLUMAT CARIAN";
		}

		$this->set('message',$result);

		$locations = $this->Location->find('all',array('conditions'=>array('Location.item_id'=>$qid)));
		$this->set('locations', $locations);

		$inspections = $this->Item->Inspection->find('all',array('conditions'=>array('Inspection.item_id'=>$qid)));
		$this->set('inspections',$inspections);

		$disposals = $this->Item->Disposal->find('all',array('conditions'=>array('Disposal.item_id'=>$qid)));
		$this->set('disposals',$disposals);

		$this->set('nosiri',$this->Item->generateSerialNo($qid));


	}

	public function get_models_ajax() {
		Configure::write ( 'debug', 3 );
		if ($this->RequestHandler->isAjax ()) {
			$this->set ( 'types', $this->Item->Type->find ( 'list', array (
			'conditions' => array (
			'Type.category_id' => $this->params ['url'] ['catId'] ),
			'recursive' => - 1 ) ) );
		}
	}

	function add_date($received_date,$type,$period){
		$date = new DateTime($received_date);
		//pr($date);
		$arrType = array('D','M','Y');
		$p = "P".$period . $arrType[$type];
		$date->add(new DateInterval($p));
		/*pr($date);
		 exit;*/
		//$this->set('warranty_period',$date->format('d-M-Y'));
		return $date->format('y-m-d');

	}
}
